<template>
    <div ref="map" style="width: 100%; height: 100%;"></div>
</template>

<script>
export default {
  name: "DeviceLocations",
  data() {
    return {
      allLocation: [],
      map: {},
    }
  },

  mounted() {
  },
  methods:{
    init(trackPoints){
      this.allLocation = trackPoints;
      console.log(this.allLocation)
      this.initMap()
    },
    searchDriving(param) {
      console.log(param)
      let that=this
      AMap.plugin('AMap.Driving', function() {
        const driving = new AMap.Driving({
          // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
          policy: AMap.DrivingPolicy.LEAST_TIME,
          map: that.map
        });

        const points = [
          {keyword: param.start.name, city: param.start.district},
          {keyword: param.end.name, city: param.end.district}
        ];
        driving.search(points);
      })
    },
    searchVehicleNum(vehicleNo) {
      this.allLocation.forEach(item=>{
        if (item.vehicleNo == vehicleNo) {
          this.map.setCenter([item.lng, item.lat])
          this.map.setZoom(15);
        }
      })
    },
    searchAddressName(address) {
      var geocoder;
      AMap.plugin('AMap.Geocoder', function() {
        geocoder = new AMap.Geocoder({
          city: '全国' // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        })
      })
      let that=this
      geocoder.getLocation(address, function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          let location=result.geocodes[0].location
          that.map.setCenter([location.lng, location.lat])
          that.map.setZoom(15);
          // // 添加标记
          // const marker = new AMap.Marker({
          //   position: [location.lng, location.lat],
          //   map: that.map,
          // });
        }
      })
    },
    initMap(){
      // 创建地图
      this.map = new AMap.Map(this.$refs.map, {
        center: [108.397128, 38.916527],
        zoom: 5,
      });

      // 添加设备定位点
      this.allLocation.forEach((location) => {
        if (location.lat && location.lng) {
          const marker = new AMap.Marker({
            position: [location.lng, location.lat],
            map: this.map,
          });

          // 添加点击事件，显示设备 ID 和定位时间
          marker.on("click", () => {
            const infoWindow = new AMap.InfoWindow({
              content: `设备 ID：${location.clientId}<br>车牌号：${location.vehicleNo}<br>定位时间：${location.time}`,
            });
            infoWindow.open(this.map, marker.getPosition());
          });
        }
      });
    }
  }
};
</script>
